package jpa.beans;

import java.io.Serializable;
import java.util.HashMap;

import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import jpa.entities.Bestelling;
import jpa.entities.BestellingPK;
import jpa.entities.Klant;
import jpa.entities.Product;
import jpa.interfaces.ProductBeanInterface;
import jpa.interfaces.WinkelmandBeanInterface;

@Remote(WinkelmandBeanInterface.class)
@Stateful(mappedName = "WinkelmandBeans")
public class WinkelmandBean implements WinkelmandBeanInterface, Serializable {
	@PersistenceContext 
	EntityManager em;
	
	private static final long serialVersionUID = -2875458375584064192L;

	private HashMap<Product, Integer> winkelwagen = new HashMap<Product, Integer>();
	private int klantid = -1;

	@Override
	public void voegProductInWinkelwagen(int aantal, Product p) {
		boolean bestaatal = false;
		System.out.println("aantal " + aantal);

		if (!winkelwagen.isEmpty()) {
			for (Product prod : winkelwagen.keySet()) {
				if (prod.getId() == p.getId()) {
					winkelwagen.put(prod, winkelwagen.get(prod) + 1);
					bestaatal = true;
				}

				if (!bestaatal) {
					winkelwagen.put(p, 1);
				}
				System.out.println(prod.getProductNaam() + "       "		+ winkelwagen.get(prod));
			}
		}
		else
		{
			System.out.println("jo");
			winkelwagen.put(p, 1);
		}

	}

	@Override
	public void leegWinkelwagen() {
		winkelwagen.clear();
	}
	
	@Override
	public HashMap<Product, Integer> getWinkelwagen() {
		return winkelwagen;
	}
	
	@Override
	public long createNewBestellingID()
	{
		System.out.println("hoi");
		Query q = em.createQuery("SELECT p FROM Bestelling p",Bestelling.class);
		q.setFirstResult(q.getResultList().size()-1);
		System.out.println(q.getResultList().size());
		Bestelling id = (Bestelling)q.getSingleResult();
		System.out.println("verkegen id: "+id.getId().getBestId());
		long newId = id.getId().getBestId();
		newId++;
		System.out.println("Nieuwe ID: "+newId);
		
		return newId;
	}
	
	
	

	@Override
	public void setKlantId(int id) {
		System.out.println("Klant id is gezet op:" + id);
		klantid = id;

	}
	
	@Override
	public int getKlantID()
	{
		return klantid;
	}

}
